<template>
  <div>
    <FixedOperation v-if="!isDialog">
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container invoice-form px-80">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="formData.invoiceDate"
                type="date"
                placeholder="请输入开票日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票金额" prop="price">
              <el-input v-model="formData.price" placeholder="请输入开票金额"
                ><template v-slot:append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票方" prop="customerId">
              <el-select
                class="w-full"
                v-model="formData.customerId"
                placeholder="请选择开票方"
                @focus="selectCustomerFn('customerId')"
              >
                <el-option
                  v-for="item in customerOption['customerId']"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联订单" prop="orderTitle">
              <el-input
                @click="activeDialog"
                placeholder="请选择关联订单"
                v-model="formData.orderTitle"
                clearable
                @clear="clearAll"
              ></el-input>
              <!-- <el-select
                v-model="formData.orderId"
                placeholder="请输入订单名称检索订单"
                class="w-full"
                suffix-icon="Search"
                remote-show-suffix
                :suffix-transition="false"
                filterable
                remote
                clearable
                @change="changeIndent"
                :remote-method="
                  val => queryIndentLimitEnt(val, formData.customerId)
                "
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in indentOptionLimitEnt"
                  :key="item.orderId"
                  :label="item.orderTitle"
                  :value="item.orderId"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票类型" prop="type">
              <el-select
                class="w-full"
                v-model="formData.type"
                placeholder="请选择发票类型"
              >
                <el-option
                  v-for="item in invoice_manage_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开票内容" prop="content">
              <el-input
                v-model="formData.content"
                placeholder="请输入开票内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票号码" prop="number">
              <el-input v-model="formData.number" placeholder="请输入发票号码">
                <template #append v-if="!props.invoiceId">
                  <el-button @click="getInvoiceData">提取诺税通发票</el-button>
                </template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经手人员" prop="handleUserId">
              <el-select
                class="w-full"
                v-model="formData.handleUserId"
                placeholder="请选择经手人员"
                @focus="selectUserFn('formhandleUserId')"
              >
                <el-option
                  v-for="item in userOption['formhandleUserId']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <avue-crud
              ref="crudProduct"
              :option="crudOptionProduct"
              :data="formData.productList"
              class="hide-required-asterisk"
            >
              <!-- <template #menu-left>
              <el-button type="primary" icon="Plus" @click="addProduct"
                >添加产品</el-button
              >
            </template> -->
              <!-- <template #serviceDateArr-form="{ row }">
                <el-date-picker
                  v-model="row.serviceDateArr"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="服务开始时间"
                  end-placeholder="服务结束时间"
                  :size="size"
                />
              </template> -->
              <template #menu="{ row }">
                <el-switch
                  v-model="row.openInvoice"
                  @change="changeSwitch(row)"
                />
                <!-- <el-button
                  plain
                  icon="Delete"
                  link
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                > -->
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>

    <!-- 关联订单弹窗 -->
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="closeDialog"
      @relatedOver="relatedOver"
    />
  </div>
</template>
<script setup name="InvoiceForm">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import {
  setInvoice,
  getInvoiceDetail,
  queryFromNuonuo
} from '@/api/invoiceManage/invoice'
import { listSalesOrderSelect } from '@/api/indentManage/indent'
import {
  crudOption, // 子表公用配置
  loadingSelect, //远程检索loading
  indentOptionLimitEnt, // 订单数据
  queryIndentLimitEnt // 检索订单数据
} from '@/hooks/dict/order'
import useTagsViewStore from '@/store/modules/tagsView'
import { isMoneyNot, maxDecimals } from '@/utils/validate'
import useUserStore from '@/store/modules/user'
import { getTreeNodeByParam, getPricipalId, myToFixed } from '@/utils/commo'
import { getWorkDay, getLatestMsg, addManage } from '@/api/system/notice'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const userOption = ref({}) //通知人员下拉
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const { invoice_manage_type, pay_type, measurement_unit, settle_type } =
  proxy.useDict(
    'invoice_manage_type', //票据类型
    'pay_type', //付款方式
    'measurement_unit', //产品单位
    'settle_type' //结算方式
  )

const props = defineProps({
  invoiceData: {
    type: Object,
    require: false,
    default: null
  },
  invoiceId: {
    type: Object,
    require: false,
    default: null
  },
  isDialog: {
    type: Boolean,
    require: false,
    default: false
  }
})
const data = reactive({
  formData: {
    customerType: 'customer' //客户类型
  },
  formRules: {
    invoiceDate: [
      {
        required: true,
        message: '请选择开票日期',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入开票金额',
        trigger: 'blur'
      },
      {
        validator: (rule, value, callback) => {
          maxDecimals(rule, value, callback, 2)
        }
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择开票方',
        trigger: 'change'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    orderTitle: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    type: [
      {
        required: true,
        message: '请选择发票类型',
        trigger: 'change'
      }
    ],
    content: [
      {
        required: true,
        message: '请选择开票内容',
        trigger: 'blur'
      }
    ],
    number: [
      {
        required: true,
        message: '请选择发票号',
        trigger: 'blur'
      }
    ],
    handleUserId: [
      {
        required: true,
        message: '请选择经手人员',
        trigger: 'change'
      }
    ]
  },

  dialogParam: {} /* 人员弹窗框参数 */,
  customerOption: {}, //客户选择下拉
  dialogParamA: {} /* 客户弹窗框参数 */,
  isDialog: false
})
const {
  formData,
  formRules,
  dialogParam,
  customerOption,
  dialogParamA,
  isDialog
} = toRefs(data)

const crudOptionProduct = ref({
  ...crudOption,
  menu: false,
  menuTitle: '是否开票',
  header: false,
  column: [
    {
      label: '开票名称',
      prop: 'invoiceName',
      cell: false,
      minWidth: '150',
      rules: [
        {
          required: true,
          message: '请输入开票名称',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '开票规格型号',
      width: '150',
      prop: 'invoiceSpecification',
      cell: false
    },
    {
      label: '单位',
      prop: 'unit',
      type: 'select',
      width: '90',
      clearable: false,
      dicData: measurement_unit,
      cell: false
    },
    {
      label: '实际售价',
      prop: 'actualPrice',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '80',
      controls: false,
      cell: false
    },
    {
      label: '数量(已开)',
      prop: 'openedNum',
      type: 'number',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '100',
      cell: false
    },
    {
      label: '数量',
      prop: 'invoiceNum',
      type: 'input',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '100',
      rules: [
        {
          required: true,
          message: '请输入数量',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            maxDecimals(rule, value, callback, 6)
          }
        }
      ],
      blur: val => {
        const { value, row } = val
        if (0 < value && value <= row.num - row.openedNum) {
          row.unOpenedPrice = myToFixed(row.actualPrice * row.invoiceNum, 6)
        } else {
          proxy.$message.error('数量不能小于0或大于剩余数量')
          row.invoiceNum = ''
        }
      },
      cell: false
    },
    {
      label: '总数量',
      prop: 'num',
      type: 'number',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '80',
      cell: false
    },
    {
      label: '金额',
      prop: 'unOpenedPrice',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '100',
      controls: false,
      cell: false
    },
    {
      label: '税率',
      width: '100',
      prop: 'taxRate',
      cell: true,
      rules: [
        {
          required: true,
          message: '请输入税率',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            maxDecimals(rule, value, callback, 6)
          }
        }
      ]
    }
  ]
})
watch(
  [
    () => route.query.invoiceId,
    () => route.query.invoiceData,
    () => props.invoiceId,
    () => props.invoiceData
  ],
  () => {
    if (route.query.invoiceId && route.name == type.name) {
      getFormData(route.query.invoiceId)
    } else if (route.query.invoiceData && route.name == type.name) {
      let invoiceData = JSON.parse(route.query.invoiceData)
      initForm(invoiceData)
    }
    if (props.invoiceId) {
      getFormData(props.invoiceId)
    } else if (props.invoiceData) {
      initForm(props.invoiceData)
    }
  },
  {
    immediate: true
  }
)
/** 获取详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  proxy.$modal.loading('加载中')
  getInvoiceDetail(id).then(async res => {
    proxy.$modal.closeLoading()
    let resData = {}
    resData = res.data
    customerOption.value['customerId'] = [
      {
        label: resData.customerName, //? resData.customerName: resData.customerId,
        id: resData.customerId //? resData.customerId : resData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderTitle: resData.orderTitle, //? resData.customerName: resData.customerId,
        orderId: resData.orderId //? resData.customerId : resData.customerName
      }
    ]
    formData.value = resData
    // 经手人员
    await getDefaultUserInfo(
      formData.value.handleUserId,
      'handleUserId',
      'formhandleUserId'
    )
  })
}

// 初始化表单
function initForm(obj) {
  formData.value.customerId = obj.customerId
  formData.value.customerName = obj.customerName
  formData.value.orderId = obj.orderId
  formData.value.orderTitle = obj.orderTitle
  formData.value.customerType = obj.customerType ? obj.customerType : 'customer'
  formData.value.productList =
    obj?.productList && obj?.productList.length > 0
      ? obj.productList.map(item => {
          return {
            ...item,
            $cellEdit: true
          }
        })
      : []
  formData.value.content =
    formData.value.productList.length > 0
      ? obj.productList.map(item => item.invoiceName).join('、')
      : ''
  // formData.value.invoicePlanId = obj.period
  if (obj.customerId) {
    customerOption.value['customerId'] = [
      {
        id: obj.customerId,
        label: obj.customerName
      }
    ]
    queryIndentLimitEnt(undefined, obj.customerId)
  }
  obj.orderId
    ? (indentOptionLimitEnt.value = [
        {
          orderId: obj.orderId,
          orderTitle: obj.orderTitle
        }
      ])
    : ''
}
// 初始化
function init() {
  isDialog.value = props.isDialog
}
// 保存
function handleSubmit(e) {
  return new Promise((resolve, reject) => {
    proxy.$refs.formRef.validate(async (valid, msg) => {
      // 产品信息信息校验
      let errMsg = []
      let err = await proxy.$refs.crudProduct.validateCellForm()
      if (err) {
        errMsg.push(`产品信息---${err[Object.keys(err)[0]][0].message}`)
      }
      if (msg) errMsg.unshift(`${msg[Object.keys(msg)[0]][0].message}`)

      if (valid && errMsg.length == 0) {
        formData.value.handleUserId = getPricipalId(
          userOption.value['formhandleUserId'],
          formData.value.handleUserId
        ).toString()
        setInvoice(formData.value).then(res => {
          // proxy.$modal.msgSuccess(formData.value.id ? '修改成功' : '新增成功')
          // 保存接口才有
          resolve(res)
          if (!isDialog.value) {
            proxy.useReturn(
              '',
              () => {
                //返回上一步
                handleReturn()
              },
              async () => {
                //继续
              }
            )
          }
          getFormData(res.data.id)
        })
      } else {
        if (errMsg.length > 0) proxy.$modal.msgError(errMsg[0])
      }
    })
  })
}

function handleReset() {
  console.log('清除')
  formData.value = {}
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}

/* 人员选择
 * @param {string}
 */
function selectUserFn(keyName) {
  dialogParam.value.type = keyName
  dialogParam.value.title = '经手人员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = false
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.defaultCheckedKeys = [formData.value[keyName]]
  dialogParam.value.dataType = 'person'
}
// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'formhandleUserId':
      userOption.value.formhandleUserId = val.selectData
      formData.value.handleUserId = val.defaultCheckedKeys.toString()
      break
  }
}
// 人员id转uuid
async function getDefaultUserInfo(val, fieldName, selectArr) {
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  } else {
    return
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(deptUserData, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

// 改变客户名称后
const changeCustomer = val => {
  // formData.value.customerName = obj[0].customerName
  // console.log('客户改变')
  formData.value.orderId = null
  formData.value.orderTitle = null
  // queryIndentLimitEnt(undefined, val)
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formData.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      // dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.tabList = [
        {
          label: '企业客户',
          name: 'customer'
        },
        {
          label: '个人客户',
          name: 'cusLink'
        },
        {
          label: '供应商',
          name: 'supplier'
        },
        {
          label: '内部单位',
          name: 'inner'
        }
      ]
      dialogParamA.value.dataType = 'person'
      break
  }
}
// 客户选择选择确定
const selectCustomerData = val => {
  // console.log('val--->', val)
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      if (formData.value.customerId !== val.defaultCheckedKeys.toString()) {
        changeCustomer(val.defaultCheckedKeys.toString())
      }
      formData.value.customerType = val.tabVal
      formData.value.customerName = val.labelData.toString()
      formData.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

// 订单赋值
function changeIndent(row) {
  console.log('row==>', row)
  let newData = JSON.parse(JSON.stringify(indentOptionLimitEnt.value))
  let obj = newData.filter(item => {
    return item.orderId == row
  })
  formData.value.orderTitle = obj[0].orderTitle
}

// 提取诺税通发票
const getInvoiceData = () => {
  if (!formData.value.orderId) return proxy.$modal.msgError('请先关联订单')
  if (!formData.value.number) return proxy.$modal.msgError('请先输入发票号码')
  let data = { orderId: formData.value.orderId, number: formData.value.number }
  queryFromNuonuo(data).then(res => {
    formData.value = { ...formData.value, ...res.data }
  })
}

/****    关联订单  开始   ***/
// 弹窗参数
const orderParams = ref()
// 打开弹窗
function activeDialog() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户名称')
    return false
  }
  const ids = [formData.value.orderId]
  console.log('ids==>', ids)
  orderParams.value = {
    visible: true, // 显示dialog
    businessId: id, // 根据id查询订单
    businessName: formData.value.customerName,
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
}

// 弹窗确认完成回调
function relatedOver(val) {
  if (val) {
    const name = orderParams.value.multiple
      ? val.map(v => v.orderTitle).toString() || ''
      : val.orderTitle
    const ids = orderParams.value.multiple
      ? val.map(v => v.orderId) || []
      : val.orderId
    const productName = orderParams.value.multiple
      ? val.map(v => v.productName) || []
      : val.productName

    formData.value.orderId = ids
    formData.value.orderTitle = orderParams.value.multiple
      ? val.map(v => v.orderTitle)
      : name
    formData.value.content = productName
    formData.value.productList =
      val?.productList && val?.productList.length > 0
        ? val.productList.map(item => {
            return {
              ...item,
              $cellEdit: true
            }
          })
        : []
  }
  closeDialog()
}

// 关闭弹窗
function closeDialog() {
  orderParams.value.visible = false
}

// el-input clear函数
function clearAll() {
  formData.value.orderId = null
  formData.value.orderTitle = null
}
/****    关联订单  end   ***/

// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

//暴露出保存方法
defineExpose({ handleSubmit })
init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.invoice-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
